package yf.mall.controller.api;

import com.github.pagehelper.PageHelper;
import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUserId;
import com.yf.service.WxPayService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import yf.mall.common.Const;
import yf.mall.entity.AccountRecordEntity;
import com.yf.response.R;
import yf.mall.entity.MallOrderEntity;
import yf.mall.enums.AccountRecordBusEnum;
import yf.mall.enums.AccountRecordStatusEnum;
import yf.mall.service.*;
import yf.mall.vo.AccountRecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import yf.mall.vo.OrderItemVo;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@RequestMapping("/api/account")


@RestController
public class ApiAccountController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private AccountRecordService recordService;

    @Autowired
    private UserService userService;

    @Autowired
    private NoticeService noticeService;

    /**
     * 转账
     *
     * @param userId
     * @param toUserId
     * @param remark
     * @param amount
     * @param type
     * @return
     */
    @RequestMapping("/transfer")
    public R transfer(@LoginUserId Long userId, Long toUserId, String remark, BigDecimal amount, Integer type) {
        userService.validateUser(userId);
        accountService.transfer(userId, toUserId, type, amount, remark);
        return R.ok();
    }

    /**
     * 账户记录
     *
     * @param userId
     * @param page
     * @param limit
     * @param type
     * @param status
     * @param bus
     * @return
     */
    @RequestMapping("/record")
    public R record(@LoginUserId Long userId, Integer page, Integer limit, Integer type, Integer status, Integer bus) {
        List<AccountRecordVo> recordVos = null;
        recordVos = recordService.findByUserId(userId, type, status, bus);
        BigDecimal downIncome = new BigDecimal(0);
        BigDecimal waitIncome = new BigDecimal(0);
        //收款页面
        if (type == null){
            if (recordVos != null && recordVos.size() > 0){
                for (AccountRecordVo recordVo : recordVos) {
                    AccountRecordEntity record = recordVo.getRecord();
                    //已收款
                    if (record.getStatus() == AccountRecordStatusEnum.DONE.getIndex()){
                        downIncome = downIncome.add(record.getAmount());
                    }
                    //未收款
                    if (record.getStatus() == AccountRecordStatusEnum.WAIT.getIndex()){
                        waitIncome = waitIncome.add(record.getAmount());
                    }
                }
            }
        }
        if (page != null) {
            PageHelper.startPage(page, limit).setOrderBy("record.status,record.id desc");
        }

        recordVos = recordService.findByUserId(userId, type, status, bus);

        return R.ok(recordVos).putExtra("downIncome",downIncome).putExtra("waitIncome",waitIncome);
    }

    @Autowired
    private MallOrderService service;

    /**
     * 收款
     *
     * @return
     */
    @RequestMapping("/payment")
    public R payment(@LoginUserId Long userId, Long recordId) {
        AccountRecordEntity recordEntity = accountService.payment(userId, recordId);

        BigDecimal autoPrice = new BigDecimal(0);
        //如果是货款在去查进货金额
        if (recordEntity.getBus() == AccountRecordBusEnum.PAYMENT.getIndex()){
            MallOrderEntity autoBuyOrder = service.findAutoBuy(recordEntity.getInfo());
            if (autoBuyOrder != null){
                autoPrice = autoBuyOrder.getPrice();
            }
        }
        return R.ok(recordEntity).putExtra("autoPrice",autoPrice);
    }


    /**
     * 充值
     *
     * @param userId
     * @param amount
     * @param request
     * @return
     */
    @RequestMapping("/commit")
    public R commit(@LoginUserId Long userId, BigDecimal amount, HttpServletRequest request) {
        String noticeUrl = ServletUriComponentsBuilder.fromContextPath(request).path(Const.ACCOUNT_CHARGE_URL).toUriString();
        String payConfig = accountService.commit(userId, amount, noticeUrl);
        return R.ok(payConfig);
    }

    /**
     * 充值成功后微信回调
     *
     * @param body
     * @return
     */
    @RequestMapping("/recharge")
    @IgnoreAuth
    public String charge(@RequestBody String body) {
        Map<String, String> map = wxPayService.handleWxNotice(body);
        String orderNo = map.get("out_trade_no");
        Integer amount = Integer.valueOf(map.get("total_fee"));
        accountService.recharge(orderNo, amount);
        return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    }


    @Autowired
    private WxPayService wxPayService;

    /**
     * Long
     * 获得当前用户的账号信息以及总佣金，
     *
     * @param userId
     * @return
     */
    @RequestMapping("/commission")
    public R queryCommission(@LoginUserId Long userId, @RequestParam(name = "year",required = false) Integer year,@RequestParam(name = "month",required = false)Integer month) {
        PageHelper.startPage(0, 100);
        List<OrderItemVo> accountVo = this.accountService.findCommission(userId,year,month);
        return R.ok(accountVo);
    }
}
